<template>
  <div style="height: 500px;">
    <el-button type="primary" @click="handleEdit">编辑</el-button>
    <el-button type="primary" @click="handleDelete">删除</el-button>
    
			<div style="padding-top:3px">
				<el-form :model="formSelect" :inline="true" ref="headerForm" label-width="80px" label-position="right">
					<el-form-item label="发票全号" prop="invoiceNo">
						<el-input  v-model="formSelect.invoiceNo" clearable />
					</el-form-item>
					<el-form-item label="开票日期" prop="invoiceNo">
						<el-date-picker v-model="formSelect.invoiceDate" type="date" clearable />
					</el-form-item>
					<el-form-item label="发票状态" prop="invoiceState">
						<el-input  v-model="formSelect.invoiceState"   clearable />
					</el-form-item>
					<el-form-item label="选择客户" prop="buysName">
						<el-input v-model="formSelect.buysName"  class="input-with-select" clearable @clear="search.buysId = ''">
							<template #append>
								<el-button icon="el-icon-search" @click="btnEventSearch(true)" />
							</template>
						</el-input>
					</el-form-item>	
			    </el-form>
			</div>
      <ag-table
        ref="agTable"
        :loading="tableLoading"
        :show-checkbox-column="true"
        :datas="tableDatas"
        :columns-config="tableListConfig"
        :page-size="pageSize"
        :current-page="pageNum"
        :total-rows="total"
        @page-change="handlePageChange"
        @cell-value-change="handleCellValChange"
        @page-size-change="handlePageSizeChange"
        @on-grid-ready="handleGridReady"
      />
    </div>
    
</template>

<script>
import AgTable from './ag-table.vue';
import { mockData } from './mock.js'
import _ from 'lodash-es'
import mitt from 'mitt'
import StatusButton from './custom-switch.vue'
export default {
  name: "App",
  components: {
    AgTable,
    // eslint-disable-next-line vue/no-unused-components
    StatusButton
  },
  created() {
    this.emitter = mitt() 
    this.emitter.on('changeSwitch', this.handlerChangeSwich);
    this.btnEventSearch()
  },
  data: function () {
    return {
      tableLoading: false,
      rowClassRules: null,
      rowId: null,
      emitter: null,
      tableDatas: [],
      pageSize: 100,
      pageNum: 1,
      total: 0,
      tableListConfig: [
      {
          field: 'no',
          headerName: '序号',          
          editable: false,
          suppressMenu: true,
          sortable: false,
          valueGetter: params => {
            console.log('params.node', params.node);
            if (params.node.data.detailId === null) {
              return '合计：'
            } else {
              return params.node ? params.node.rowIndex + 1 : null;
            }
          }
        },
        { headerName: '入账标志', field: 'isAccount', type: 'rightAligned', cellRenderer: 'StatusButton' },
        { headerName: '发票代号', field: 'invoiceCode' },
        { headerName: '发票号码', field: 'invoiceNumber',type: 'rightAligned',},
        { headerName: '发票全号', field: 'invoiceNo', },
        { headerName: '开票日期', field: 'invoiceDate',},
        { headerName: '销货方单位编号', field: 'salesId',},
        { headerName: '销货方单位名称', field: 'gold' },
        { headerName: '购买方单位编号', field: 'silver' },
        { headerName: '购买方单位名称', field: 'salesName' },
        { headerName: '顺序号', field: 'detailId' },
        { headerName: '货物名称', field: 'goodsName' },
        { headerName: '货物明细', field: 'goodsNameDetails' },
        { headerName: '规格型号', field: 'spec' },
        { headerName: '单位', field: 'unit' },
        { headerName: '单价', field: 'unitPrice' },
        { headerName: '数量', field: 'number' },
        { headerName: '金额', field: 'money' },
        { headerName: '税率', field: 'taxRate' },
        { headerName: '税额', field: 'tax' },
        { headerName: '价税金额', field: 'totalAmount' },
        { headerName: '类别', field: 'invoiceType' },
        { headerName: '状态', field: 'invoiceState' },
        { headerName: '备注', field: 'remark' },
      ],
      formSelect: {},
      executedParam: {}
    };
  },
  methods: {
    // 查询
    btnEventSearch(isEvent) {
      const filterCondition = isEvent ? this.formSelect : this.executedParam;
      const params = {
        pageSize: this.pageSize,
        pageNum: this.pageNum,
        ...filterCondition
      }
      console.log('调接口参数', JSON.stringify(params));
      /* queryNotice(params)
        .then(res => {
          if (isEvent) this.executedParam = _.cloneDeep(this.formSelect);
          this.tableDatas = mockData;
          this.total = 54260;
        })
        .catch(() => {}); */
        setTimeout(() => {
          if (isEvent) this.executedParam = _.cloneDeep(this.formSelect);
          this.tableDatas = mockData;
          this.total = 54260;
        }, 500);
    },
    //增加
		add() {
			this.dialog.save = true
			this.$nextTick(() => {
				this.$refs.saveDialog.open()
			})
		},
		//勾选编辑
		edit() {
			if (this.selection === null || this.selection.length === 0) {
				this.$alert('请选择要编辑的数据！', "提示", { type: 'error' })
				return;
			}
			let row = this.selection[0]
			this.dialog.save = true
			this.$nextTick(() => {
				this.$refs.saveDialog.open('edit').setData(row)
			})
		},
		//勾选删除
		async batch_del() {
			this.$confirm(`确定删除选中的 ${this.selection.length} 项吗？`, '提示', {
				type: 'warning'
			}).then(async () => {
				const loading = this.$loading();
				let ids = this.selection.map(x => x.id)
				var res = await this.$API.financeInvoiceOut.delete.post(ids)
				if (res.code === 200) {
					this.$refs.agTable.refresh()
					this.$message.success('删除成功')
				} else {
					this.$message.error('删除失败：' + res.message)
				}
				loading.close()
			}).catch(() => {

			})
		},
    handleCellValChange(row) {
      console.log('切换的行', row);
    },
    handleGridReady() {
      setTimeout(() => {
        let pinnedBottomData = this.generatePinnedBottomData();
        const filteredBottomData = _.mapValues(pinnedBottomData, function(value) {  
          if (value && !Number.isInteger(value)) {
            return value.toFixed(2);  
          } else {
            return value
          }
        }); 
        this.$refs.agTable.gridApi.setPinnedBottomRowData([filteredBottomData]);  
        
      }, 500);
    },
    // 改变展示条数
    handlePageSizeChange(pageSize) {
      this.pageSize = pageSize;
      this.pageNum = 1;
      this.btnEventSearch();
    },
    // 页数变化触发的回调
    handlePageChange(pageNum) {
      this.pageNum = pageNum;
      this.btnEventSearch();
    },
    //勾选编辑
		handleEdit() {
      const selectedNodes = this.$refs.agTable.getSelectedRows();
			if (selectedNodes === null || selectedNodes.length === 0) {
				this.$alert('请选择要编辑的数据！', "提示", { type: 'error' })
				return;
			}
			let row = selectedNodes[0]
      console.log('编辑的行', row);
			/* this.dialog.save = true
			this.$nextTick(() => {
				this.$refs.saveDialog.open('edit').setData(row)
			}) */
		},
    // 获取选中的行的数据
    handleDelete() {
      const selectedNodes = this.$refs.agTable.getSelectedRows();
      if (!selectedNodes.length) {
        this.$message.warning('请先选中一些数据');
        return;
      }
      this.$confirm(`确定删除选中的 ${selectedNodes.length} 项吗？`, '提示', {
				type: 'warning'
			}).then(async () => {
        let ids = selectedNodes.map(x => x.id)
        console.log('选择的IDS', ids);
				/* const loading = this.$loading();
				var res = await this.$API.financeInvoiceOut.delete.post(ids)
				if (res.code === 200) {
					this.btnEventSearch()
					this.$message.success('删除成功')
				} else {
					this.$message.error('删除失败：' + res.message)
				}
				loading.close() */
			}).catch(() => {

			})
    },
    generatePinnedBottomData(){
      // 生成一个包含空值的行数据
      let result = {};

      this.$refs.agTable.columnApi.getAllGridColumns().forEach(item => {
          result[item.colId] = null;
      });
      return this.calculatePinnedBottomData(result);
  },
    calculatePinnedBottomData(target){
      let columnsWithAggregation = ['unitPrice','number','money','tax','taxRate', 'totalAmount']; // 需要进行合计的列
        columnsWithAggregation.forEach(element => {
            this.$refs.agTable.gridApi.forEachNodeAfterFilter((rowNode) => {
                if (rowNode.data[element]) {
                  target[element] += Number((+rowNode.data[element]).toFixed(2));
                }
            });
            /* if (target[element]){
              target[element] = `${(+target[element]).toFixed(2)}`;  
            } */
        })
        return target;
    },
      // 表格状态按钮回调
    changeSwitchVal(field, node, val) {
      const mdata = node.data;
      mdata[field] = val;
      console.log('mdata', mdata[field]);
      this.$refs.agTable.setRowData(mdata);
    },
    //入帐标志
    handlerChangeSwich(row) {
      console.log('切换的行', row);
      /* let me = this
			//1.还原数据
			let reqData = { id: row.id, IsAccount: !!row.isAccount }
			//2.执行加载
			row.$switch_isAccount = true
			//3.等待接口返回后改变值
			setTimeout(async function () {
				await me.$API.financeSubject.account.put(reqData)
				delete row.$switch_isAccount
			}, 1000) */
    }
  },
};

</script>
<style lang="scss">
.full {
  height: 100%;
}
.flex-column {
  display: flex;
  flex-flow: column nowrap;
  height: 100%;
}
.height-300 {
  height: 300px;
}
</style>